import { BadRequestException } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';

/**
 * 图片上传拦截器
 * 封装了图片上传的通用配置，包括文件大小限制和类型验证
 */
export const ImageUploadInterceptor = (fieldName: string = 'file', options?: {
  maxSize?: number; // 最大文件大小（字节）
  allowedMimeTypes?: string[]; // 允许的MIME类型
}) => {
  const defaultMaxSize = 5 * 1024 * 1024; // 默认5MB
  const defaultAllowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  
  const multerOptions: MulterOptions = {
    limits: {
      fileSize: options?.maxSize || defaultMaxSize,
    },
    fileFilter: (req, file, callback) => {
      // 验证文件类型
      const allowedTypes = options?.allowedMimeTypes || defaultAllowedMimeTypes;
      if (!allowedTypes.includes(file.mimetype)) {
        return callback(
          new BadRequestException(`只允许上传以下类型的文件: ${allowedTypes.map(type => type.split('/')[1]).join('、')}`), 
          false
        );
      }
      callback(null, true);
    },
  };
  
  return FileInterceptor(fieldName, multerOptions);
};

/**
 * 默认的图片上传拦截器（使用file字段名，5MB限制）
 */
export const DefaultImageUploadInterceptor = ImageUploadInterceptor();
